package lewiszlw.sso.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lewiszlw.sso.server.config.RestConfig;
import lewiszlw.sso.server.entity.PartnerProductEntity;
import lewiszlw.sso.server.entity.ShipmentEntity;
import lewiszlw.sso.server.mapper.PartnerProductMapper;
import lewiszlw.sso.server.mapper.ShipmentMapper;
import lewiszlw.sso.server.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.util.*;

/**
 * @ClassName: ShipmentService
 * @Decription: 此处填写类文件说明
 * @Author: IDai
 * @Date: 2021-07-15 14:49 星期四
 **/
@Service
public class ShipmentService {

    @Autowired
    private ShipmentMapper shipmentMapper;
    @Autowired
    private PartnerProductMapper productMapper;
    @Autowired
    private RestTemplate restTemplate;

    public JSONObject sendShipmentMethod(int shipId, int productId) {
        String body = "";
        try {
            CommonUtil commonUtil = new CommonUtil();
            List<String> params = new ArrayList<>();
            String token = "7s2h3843hjj290726khsnn782ns0s76ss";
            String timestamp = String.valueOf(System.currentTimeMillis());
            String eventId = String.valueOf(System.currentTimeMillis());
            params.add(eventId);
            params.add(timestamp);
            params.add(token);
            Collections.sort(params);
            String localSignature = StringUtils.join(params, "");
            String signature = commonUtil.sha256(localSignature);
            String shipmentUrl = "http://api.nanofintax.com/channel/api/partner?signature=" + signature + "&timestamp=" + timestamp + "&eventId=" + eventId;
            ShipmentEntity shipmentEntity = shipmentMapper.queryShipmentById(shipId);
            PartnerProductEntity partnerProductEntity = productMapper.queryPartnerProductById(productId);
            shipmentEntity.setPartnerProductInfo(partnerProductEntity);
            JSONObject json = (JSONObject) JSONObject.toJSON(shipmentEntity);
            body = send(shipmentUrl, json, "UTF-8");

            System.out.println("有度税智发货接口返回数据:"+body);
        } catch (Exception e) {
            e.getMessage();
        }
        return JSONObject.parseObject(body);

    }

    /**
     * 发送post请求
     * @param url  路径
     * @param jsonObject  参数(json类型)
     * @param encoding 编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader("utf-8","application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

}
